import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yysk_app/model/market_model/market_incubation_list_model.dart';
import 'package:yysk_app/net/api/market_url.dart';
import 'package:yysk_app/net/api/pay_url.dart';
import 'package:yysk_app/net/api/product_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/main/main_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_exchange_psw.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_real_name_auth_page.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/investmoney/investmoney_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/utils/helper.dart';

class MarketRobBuyController extends GetxController {
  var title = '校验交易密码'.obs;
  var hradTitle = '省心抢'.obs;
  var type = '1'.obs; //0 批量出售 1批量取消出售
  var num = '0'.obs; //
  var list = RxList<MarketIncubationListModelItem>([]);
  var listChoose = RxList<MarketIncubationListModelItem>([]);
  var password = ''.obs;
  int pageNum = 1;
  int pageSize = 10;
  var count = 0.obs;
  var isBatch = false.obs;
  final ScrollController scrollController = ScrollController();
  var rightTxt = '暂停抢购'.obs;
  RxBool isAllSelect = false.obs;
  GlobalController globalController = Get.find();
  //
  final hasWallet = RxString('0.00');

  @override
  void onInit() {
    super.onInit();
    getListData();
    // type.value = Get.parameters['type'] ?? Get.arguments['type'] ;
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        getListData(loadMore: true);
      }
    });
    globalController.getXPayToken().then((r) {
      getPlatWallet();
    });
  }

  void getPlatWallet() {
    http.netFetch<dynamic>(
      PayUrl.getPlatWalletBalance,
      success: (res) {
        hasWallet.value = '${res.data}';
      },
    );
  }

  @override
  void onClose() {
    super.onClose();
    scrollController.dispose();
  }
  
  Future<void> handleRefresh() async {
    getListData();
    isAllSelect.value = false;
    globalController.getXPayToken().then((r) {
      getPlatWallet();
    });
  }

  void investmoney() {
    Get.toNamed('${InvestmoneyPage.path}?type=1&channel=DIN_PAY');
  }

  //去实名
  toSm({required BuildContext context}) async {
    await showConfirmDialog(
      context: context,
      message: '请先完成实名认证',
      messages: [],
      fontSize: 16.px,
      actions: [
        ActionModel(
          label: '取消',
          colorStart: AppColors.backgroundColorGreyF8,
          colorEnd: AppColors.backgroundColorGreyF8,
          fontColor: AppColors.fontColor,
          onPressed: () {},
        ),
        ActionModel(
          label: '立即认证',
          onPressed: () {
            Get.toNamed(SettingRealNameAuthPage.path);
          },
        ),
      ],
    );
  }

  //是否开通交易密码
  Future<dynamic> isSetPayPassword() async {
    try {
      showConfirmDialog(
        context: Get.context!,
        message: '请先设置交易密码',
        messages: [],
        fontSize: 16.px,
        actions: [
          ActionModel(label: '取消', onPressed: () {}),
          ActionModel(
            label: '前往设置',
            onPressed: () {
              Get.toNamed(ChangeExchangePassword.path);
            },
          ),
        ],
      );
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  getListData({loadMore = false}) {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }

    try {
      http.netFetch<MarketIncubationListModel>(
        MarketUrl.getCollectionPage,
        params: {'pageNum': pageNum, 'pageSize': 20},
        method: Method.post,
        success: (result) {
          List<MarketIncubationListModelItem> items = result.data?.list ?? [];
          if (loadMore && items.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            list.clear();
          }
          list.addAll(items);
          for (var element in list) {
            if(element.isSelect==false){
                    isAllSelect.value = false;
            }
          }
        },
      );
    } catch (e) {
      if (loadMore) {
        pageNum--;
      }
    }
  }

  //出售的列表数据
  Future<void> chooseListSell(dynamic collectionId) async {
    for (var element in list) {
      if (element.collectionId == collectionId) {
        element.isSelect = !element.isSelect!;
      }
    }

    listChoose.value = [];
    for (var element in list) {
      if (element.isSelect == true) {
        listChoose.add(element);
      }
    }
    isAllSelect.value = true;
    for (var element in list) {
      if (element.isSelect == false) {
        isAllSelect.value = false;
      }
    }
    count++;
  }

  //全选
  Future<void> selectAll() async {
    count++;
    //先判断是不是全选状态
    isAllSelect.value = true;
    for (var element in list) {
      if (element.isSelect == false) {
        isAllSelect.value = false;
      }
    }
    //后根据判断来处理
    if (isAllSelect.value == false) {
      listChoose.value = [];
      for (var element in list) {
        element.isSelect = true;
        listChoose.add(element);
      }
      isAllSelect.value = true;
    } else {
      listChoose.value = [];
      isAllSelect.value = false;
      for (var element in list) {
        element.isSelect = false;
      }
    }
  }

  //校验交易密码是否正确
  Future<void> verifySecurityPassword(Function(bool res) callback) async {
    http.netFetch<dynamic>(
      ProductApi.verifySecurityPassword,
      params: {'payPassword': password.value},
      method: Method.post,
      success: (result) {
        if (result.code == 200) {
          callback(true);
        }
      },
    );
  }
}
